/*
============================================================================
 Name        : dd_log.c
 Author      : Jian (raphyer@hotmail.com)
 Version     :
 Copyright   : GPL
 Description : dd_log.c - source file
============================================================================
*/

/* INCLUDE FILES */
#include "dd_log.h"
#include "dd_define.h"
#include "dd_utf8.h"
#include "pd_file.h"
#include "pd_lui.h"


#define __MAX_LOG_FILE_SIZE  (4 * 1024 * 1024)
#define __MAX_LOG_BUF_SIZE    256 
#define __LOG_FILE_NAME_LEN   10


static pd_file* __logger  = NULL ;
static DD_INT  loop       = 1 ;
static DD_BOOL __logging  = DD_FALSE ;


static void _get_log_file() 
{
    DD_CHAR path[DD_MAX_FLIE_LEN + 1] = {0} ;
    DD_CHAR* name                     = DD_NULL ;

    if (__logger) {
        pd_file_close(__logger) ;
        __logger = NULL ;
    }
    
    if (pd_create_and_set_log_folder((DD_UTF8*)path, DD_MAX_FLIE_LEN - __LOG_FILE_NAME_LEN) < 0) 
        return ;

    name = path + DD_STRLEN(path) ;

    for (; loop < 10000; loop++) {
        DD_UNICODE* uname = NULL ;
        dd_snprintf(name, __LOG_FILE_NAME_LEN, "%04d.log", loop) ;
        uname = dd_utf8_to_unicode((const DD_UTF8*)path) ;
        
        if (!pd_file_exist(uname)) {
            __logger = pd_file_open(uname, PD_FILE_CREATE) ;
            DD_FREE(uname) ;
            break; 
        }

        DD_FREE(uname) ;
    }
}

void dd_log(const char* format, ...) 
{
    DD_CHAR buf[__MAX_LOG_BUF_SIZE + 1] = {0} ;
    va_list ap ;

    if (__logging) return ;

    __logging = DD_TRUE ;

    __DD_ASSERT_DEFENSE(__logger, return) ;

    if (pd_file_size(__logger) >= __MAX_LOG_FILE_SIZE) 
        _get_log_file() ;

    va_start(ap, format) ;
    dd_vsnprintf(buf, __MAX_LOG_BUF_SIZE, format, ap) ;
    va_end(ap) ;

    pd_file_write(__logger, buf,  DD_STRLEN(buf)) ;
    pd_file_write(__logger, "\n", 1) ;
    pd_file_flush(__logger) ;

    __logging = DD_FALSE ;
}


void dd_log_init() 
{
    dd_log_deinit() ;
    _get_log_file() ;
}

void dd_log_deinit() 
{
    /* Add the __logging defense is to avoid the case : 
    the __logger was really closed in pd_file_close(__logger) ;
    but it use the dd_log() to print some log,
    and now the __logger was closed but it is not set to DD_NULL yet 
    so call dd_log() will crash the application .
    */
    __logging = DD_TRUE ;

    if (__logger) {
        pd_file_close(__logger) ;
        __logger = DD_NULL ;
    }

    __logging = DD_FALSE ;
}

/* End of File */
